const db = require("../common/db/index");

module.exports = {
    // 获取分类详情
    detail(id) {
        return new Promise((resolve, reject) => {
            const sql = 'SELECT id, cate,cate_name,cate_url FROM pre_cate WHERE id = ?';
            db.query(sql, [Number(id)])
                .then(
                    result => {
                        resolve(result)
                    },
                    err => {
                        reject(err)
                    }
                )

        })
    },
    // 获取分类列表
    list() {
        return new Promise((resolve, reject) => {
            const sql = 'SELECT id, cate, cate_name, cate_url FROM pre_cate';
            db.query(sql)
                .then(
                    result => {
                        resolve(result)
                    },
                    err => {
                        reject(err)
                    }
                )

        })
    },
    // 搜索分类（按分类名模糊查询）
    search(keyword) {
        return new Promise((resolve, reject) => {
            const sql = 'SELECT * FROM pre_cate WHERE cate_name LIKE ?';
            db.query(sql, [`%${keyword}%`])
                .then(
                    result => {
                        resolve(result)
                    },
                    err => {
                        reject(err)
                    }
                )
        })
    },
    // 添加分类
    add(cate, cate_name, cate_url) {
        return new Promise((resolve, reject) => {
            const sql = 'INSERT INTO pre_cate (cate, cate_name, cate_url) VALUES (?, ?, ?)';
            db.query(sql, [cate, cate_name, cate_url])
                .then(
                    result => {
                        resolve(result)
                    },
                    err => {
                        reject(err)
                    }
                )

        })
    },
    // 批量添加二级分类
    addBatch(parentCate, childCates) {
        return new Promise(async (resolve, reject) => {
            try {
                if (!parentCate || !childCates || childCates.length === 0) {
                    reject({
                        code: -1,
                        msg: "参数不完整"
                    })
                    return
                }

                if (childCates.length > 3) {
                    reject({
                        code: -1,
                        msg: "二级导航最多只能添加3个"
                    })
                    return
                }

                // 批量插入数据 - 使用循环插入确保兼容性
                const sql = 'INSERT INTO pre_cate (cate, cate_name, cate_url) VALUES (?, ?, ?)';
                const insertPromises = childCates.map(cate_name => {
                    return db.query(sql, [parentCate, cate_name, ''])
                })

                await Promise.all(insertPromises)
                    .then(
                        results => {
                            resolve({
                                code: 200,
                                msg: "批量添加分类成功",
                                result: results
                            })
                        },
                        err => {
                            reject({
                                code: -1,
                                msg: "批量添加分类失败",
                                err: err
                            })
                        }
                    )
            } catch (err) {
                reject({
                    code: -1,
                    msg: "批量添加分类失败",
                    err: err
                })
            }
        })
    },
    // 修改分类
    modify(cate, cate_name, cate_url, id) {
        return new Promise((resolve, reject) => {
            const sql = 'UPDATE pre_cate SET cate = ?, cate_name = ? , cate_url = ? WHERE id = ?';
            db.query(sql, [cate, cate_name, cate_url, id])
                .then(
                    result => {
                        resolve(result)
                    },
                    err => {
                        reject(err)
                    }
                )

        })
    },
    // 删除分类
    remove(id) {
        return new Promise((resolve, reject) => {
            const sql = 'DELETE FROM pre_cate WHERE id = ?';
            db.query(sql, [id])
                .then(
                    result => {
                        resolve(result)
                    },
                    err => {
                        reject(err)
                    }
                )

        })
    },
    // 删除一级分类及其所有二级分类
    removeByParentCate(parentCate) {
        return new Promise(async (resolve, reject) => {
            try {
                // 删除该一级分类下的所有分类记录（包括一级和二级）
                const sql = 'DELETE FROM pre_cate WHERE cate = ?';
                const result = await db.query(sql, [parentCate]);
                resolve({
                    code: 200,
                    msg: "删除分类成功",
                    result: result
                });
            } catch (err) {
                reject({
                    code: -1,
                    msg: "删除分类失败",
                    err: err
                });
            }
        });
    },
    // 获取分类列表（分页）
    items(page_num, page_size) {
        return new Promise(async (resolve, reject) => {
            const rows = await db.query(`SELECT count(*) as total FROM pre_cate`);
            let page_num2 = ((parseInt(page_num) - 1) * parseInt(page_size))
            let page_size2 = (parseInt(page_size))
            let sql = `select * from pre_cate limit ${page_num2} , ${page_size2}`
            await db.query(sql)
                .then(
                    data => {
                        resolve({
                            total: rows[0].total,
                            data
                        })
                    },
                    err => {
                        reject(err)
                    }
                )

        })
    }
}